import React, {
  useMemo,
  useState,
  useCallback,
  useRef,
  useEffect,
} from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  InteractionManager,
  Animated,
  Easing,
  Platform,
} from 'react-native';
import { WebView } from 'react-native-webview';
import { COLORS } from '../styles/constants';

/**
 * WebAmap 在首页展示真实高德地图（Web 版）
 * props:
 * - city: 当前城市名
 * - region: { latitude, longitude }
 * - attractions: Array<{ id, name, latitude, longitude, rating, address }>
 * - onPressMarker: (attraction) => void
 * - currentLocation: { latitude, longitude } 用户当前位置
 */
const WebViewCache = (() => {
  let hydrated = false;
  return {
    shouldHydrate() {
      return hydrated;
    },
    markHydrated() {
      hydrated = true;
    },
  };
})();

const WebAmap = ({
  city,
  region,
  attractions = [],
  onPressMarker,
  currentLocation,
  onLocationPress,
  style,
  heading = 0, // 设备朝向（度）
}) => {
  // ==== 所有 useState 和 useRef 必须在最顶层，不能有任何条件判断 ====
  const [webMapReady, setWebMapReady] = useState(true);
  const [shouldRenderMap, setShouldRenderMap] = useState(true);
  
  const webViewRef = useRef(null);
  const headingRef = useRef(heading);
  const touchStartY = useRef(0);
  const touchStartX = useRef(0);
  const isTouchingMap = useRef(false);
  const scrollThreshold = useRef(10);
  const shimmerOpacity = useRef(new Animated.Value(0)).current;
  const blurOpacity = useRef(new Animated.Value(0)).current;
  const backdropOpacity = useRef(new Animated.Value(0)).current;

  // ==== 所有 useEffect 必须在 useState/useRef 之后，不能有任何条件判断 ====
  
  // 同步更新 headingRef
  useEffect(() => {
    headingRef.current = heading;
  }, [heading]);

  // 标记已加载
  useEffect(() => {
    WebViewCache.markHydrated();
  }, []);

  // 实时更新用户位置和方向（添加防抖）
  useEffect(() => {
    
    if (webMapReady && webViewRef.current && currentLocation) {
      // 防抖：避免过于频繁的 injectJavaScript 调用
      const timer = setTimeout(() => {
        if (!webViewRef.current) {
          return;
        }
        
        // 从 ref 读取最新的 heading，而不是闭包里的旧值
        const currentHeading = headingRef.current;
      
      const script = `
      (function(){
        if (!window.map) {
          return;
        }
        
        var userLocation = [${Number(currentLocation.longitude)}, ${Number(currentLocation.latitude)}];
        var userHeading = ${Number.isFinite(Number(currentHeading)) ? Number(currentHeading) : 0};
        
        // 更新用户位置标记（调用带动画的 window.ensureUserMarker）
        if (window.ensureUserMarker && Array.isArray(userLocation)) {
          window.ensureUserMarker(userLocation, userHeading);
        }
      })();
      true;
    `;
    
        webViewRef.current.injectJavaScript(script);
      }, 100); // 100ms 防抖

      return () => clearTimeout(timer);
    }
  }, [currentLocation, heading, webMapReady]); // heading 作为依赖保留，触发 useEffect，但内部读 headingRef 获取最新值

  // 移除加载动画逻辑

  const html = useMemo(() => {
    if (!shouldRenderMap) {
      return '';
    }

    // 默认使用乌鲁木齐坐标（而不是上海）
    const defaultCenterLng = Number.isFinite(parseFloat(region?.longitude))
      ? parseFloat(region.longitude)
      : 87.6168;
    const defaultCenterLat = Number.isFinite(parseFloat(region?.latitude))
      ? parseFloat(region.latitude)
      : 43.8256;

    let userLocationForMap = null;
    if (
      currentLocation &&
      Number.isFinite(Number(currentLocation.longitude)) &&
      Number.isFinite(Number(currentLocation.latitude))
    ) {
      userLocationForMap = {
        lng: Number(currentLocation.longitude),
        lat: Number(currentLocation.latitude),
      };
    }
    
    // heading 只用于初始化，后续通过 injectJavaScript 更新，不应触发 HTML 重建
    const initialHeading = 0;

    const coordDiagnostics = [];

    const sanitizeCoordinate = (rawLng, rawLat, index, attraction) => {
      let lng = Number(rawLng);
      let lat = Number(rawLat);

      const isLngFinite = Number.isFinite(lng);
      const isLatFinite = Number.isFinite(lat);

      const lngInRange = isLngFinite && Math.abs(lng) <= 180;
      const latInRange = isLatFinite && Math.abs(lat) <= 90;

      if (
        (!lngInRange || !latInRange) &&
        isLatFinite &&
        Math.abs(Number(rawLng)) <= 90 &&
        Math.abs(Number(rawLat)) <= 180
      ) {
        // suspect swapped lat/lng
        coordDiagnostics.push({
          type: 'swap',
          id: attraction?.id ?? index,
          name: attraction?.name,
          original: { longitude: rawLng, latitude: rawLat },
          corrected: { longitude: Number(rawLat), latitude: Number(rawLng) },
        });
        lng = Number(rawLat);
        lat = Number(rawLng);
      }

      if (
        !Number.isFinite(lng) ||
        !Number.isFinite(lat) ||
        Math.abs(lng) < 0.000001 ||
        Math.abs(lat) < 0.000001
      ) {
        const fallbackLng = defaultCenterLng + (index % 5) * 0.01;
        const fallbackLat = defaultCenterLat + (index % 5) * 0.01;
        coordDiagnostics.push({
          type: 'fallback',
          id: attraction?.id ?? index,
          name: attraction?.name,
          original: { longitude: rawLng, latitude: rawLat },
          fallback: { longitude: fallbackLng, latitude: fallbackLat },
        });
        return { lng: fallbackLng, lat: fallbackLat };
      }

      return { lng, lat };
    };

    const markers = attractions.map((a, index) => {
      const { lng, lat } = sanitizeCoordinate(
        a?.longitude,
        a?.latitude,
        index,
        a,
      );

      return {
        position: [lng, lat],
        title: String(a?.name || `景点${index + 1}`),
        content:
          '<div style="display: flex; flex-direction: column; align-items: center; margin: 0; padding: 0; position: relative;">' +
          '<div style="width: 40px; height: 40px; border-radius: 20px; overflow: hidden; margin-bottom: 1px; border: 2px solid #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.3);">' +
          '<img src="' +
          (a?.image || 'https://picsum.photos/40/40') +
          '" ' +
          'style="width: 100%; height: 100%; object-fit: cover;" />' +
          '</div>' +
          '<div style="font-weight: bold; font-size: 10px; color: #fff; text-align: center; max-width: 60px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-shadow: 1px 1px 2px rgba(0,0,0,0.8); line-height: 1.1;">' +
          (a?.name || '景点' + (index + 1)) +
          '</div>' +
          '</div>',
        id: String(a?.id ?? index),
      };
    });

    const centerLng = defaultCenterLng;
    const centerLat = defaultCenterLat;

    return `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
      <title>高德地图</title>
      <script src="https://webapi.amap.com/maps?v=2.0&key=3662eb89e8bcc16dfe4f598f90856330&plugin=AMap.MarkerCluster"></script>
      <style>
        html, body, #container { 
          height: 100%; 
          width: 100%; 
          margin: 0; 
          padding: 0;
        }
        #container {
          /* 优化触摸响应 */
          touch-action: pan-x pan-y;
          -webkit-overflow-scrolling: touch;
        }
      </style>
    </head>
    <body>
      <div id="container"></div>
      <script>
        window.onload = function () {
          try {
            var defaultCenter = new AMap.LngLat(${centerLng}, ${centerLat});

            window.map = new AMap.Map('container', {
              resizeEnable: true,
              center: defaultCenter,
              zoom: 10,
              minZoom: 8,
              maxZoom: 18,
              mapStyle: 'amap://styles/fresh',
              animateEnable: false,
              jogEnable: false,
              pitchEnable: false,
              rotateEnable: false,
              features: ['bg','road'],
              viewMode: '2D',
              showLabel: false,
              showIndoorMap: false,
              showTraffic: false,
              showBuildings: false,
              showPOI: false,
              showScale: false,
              showCompass: false,
              // 禁用所有默认控件
              toolbar: false,
              toolBar: false,
              scaleCtrl: false,
              zoomCtrl: false
            });

            var markers = ${JSON.stringify(markers)};
            var instances = [];
            var overlayEntries = [];
            var overlayUpdateId = null;
            var container = document.getElementById('container');
            var userLocation = ${
              userLocationForMap
                ? `[${userLocationForMap.lng}, ${userLocationForMap.lat}]`
                : 'null'
            };
            var userHeading = ${initialHeading};

            // 优化：批量更新覆盖元素位置
            function scheduleOverlayUpdate() {
              if (overlayUpdateId) return;
              overlayUpdateId = requestAnimationFrame(function() {
                overlayEntries.forEach(function(entry) {
                  var pixel = map.lngLatToContainer(entry.lngLat);
                  if (pixel) {
                    entry.div.style.transform = 'translate(' + (pixel.x + 5) + 'px, ' + (pixel.y - 45) + 'px)';
                  }
                });
                overlayUpdateId = null;
              });
            }

            // 优化：预创建共享的地图标记图标
            var sharedSvgString = '<svg width="18" height="24" viewBox="0 0 18 24" xmlns="http://www.w3.org/2000/svg">' +
              '<path d="M9 1C6 1 3 3.5 3 7c0 3.5 6 10 6 10s6-6.5 6-10c0-3.5-3-6-6-6z" fill="#ff6b35" stroke="#fff" stroke-width="1.2"/>' +
              '<circle cx="9" cy="7" r="2.5" fill="#fff"/>' +
              '</svg>';
            var sharedIcon = new AMap.Icon({
              size: new AMap.Size(18, 24),
              image: 'data:image/svg+xml;base64,' + btoa(sharedSvgString),
              imageSize: new AMap.Size(18, 24)
            });

            // 批量创建标记和信息气泡
            var fragment = [];
            markers.forEach(function(m, index) {
              if (!Array.isArray(m.position)) return;
              
              var marker = new AMap.Marker({
                position: new AMap.LngLat(m.position[0], m.position[1]),
                title: String(m.title || ''),
                icon: sharedIcon,
                anchor: 'bottom-center',
                extData: { id: m.id, title: m.title }
              });
              
              // 创建信息气泡（显示景点图片和名字）
              var infoDiv = document.createElement('div');
              infoDiv.innerHTML = m.content;
              infoDiv.style.position = 'absolute';
              infoDiv.style.pointerEvents = 'auto';
              infoDiv.style.cursor = 'pointer';
              infoDiv.style.zIndex = '1000';
              infoDiv.style.willChange = 'transform';
              container.appendChild(infoDiv);

              overlayEntries.push({
                div: infoDiv,
                lngLat: new AMap.LngLat(m.position[0], m.position[1])
              });

              // 点击事件（信息气泡）
              var touchStartTime = 0;
              infoDiv.addEventListener('touchstart', function(evt) {
                evt.stopPropagation();
                touchStartTime = Date.now();
              }, { passive: false });

              infoDiv.addEventListener('touchend', function(evt) {
                evt.stopPropagation();
                evt.preventDefault();
                if (Date.now() - touchStartTime < 300) {
                  window.ReactNativeWebView && window.ReactNativeWebView.postMessage(
                    JSON.stringify({ type:'markerClick', id: m.id, title: m.title })
                  );
                }
              }, { passive: false });
              
              // 点击事件（地图标记）
              marker.on('click', function(){
                window.ReactNativeWebView && window.ReactNativeWebView.postMessage(
                  JSON.stringify({ type:'markerClick', id: m.id, title: m.title })
                );
              });
              
              fragment.push(marker);
              instances.push(marker);
            });

            // 批量添加标记（一次性渲染）
            if (fragment.length > 0) {
              map.add(fragment);
            }

            // 初始更新覆盖元素位置
            scheduleOverlayUpdate();

            // 监听地图事件
            map.on('mapmove', scheduleOverlayUpdate);
            map.on('zoomchange', scheduleOverlayUpdate);
            // 立即通知React Native地图准备好（不等待complete事件）
            window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ type:'mapReady' }));

            // 异步调整视野（不阻塞初始渲染）
            if (instances.length > 0) {
              setTimeout(function() {
                map.setFitView(instances, false, [60, 60, 60, 60], 14);
                if (userLocation && window.ensureUserMarker) {
                  window.ensureUserMarker(userLocation, userHeading);
                }
              }, 100);
            } else if (userLocation && window.ensureUserMarker) {
              setTimeout(function() {
                window.ensureUserMarker(userLocation, userHeading);
                map.setZoomAndCenter(13, new AMap.LngLat(userLocation[0], userLocation[1]));
              }, 100);
            }

            window.ensureUserMarker = function(positionArr, headingAngle) {
              if (!Array.isArray(positionArr)) return;
              headingAngle = headingAngle || 0;
              var lngLat = new AMap.LngLat(positionArr[0], positionArr[1]);

              // 确保阴影滤镜已定义
              if (!document.getElementById('shadow-def')) {
                var defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
                defs.id = 'shadow-def';
                defs.innerHTML = '<filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">' +
                  '<feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#000" flood-opacity="0.25"/>' +
                  '</filter>';
                // 尝试附加到页面上任意一个SVG，以便全局使用
                var anySvg = document.querySelector('svg');
                if (anySvg) {
                  anySvg.insertBefore(defs, anySvg.firstChild);
                }
              }

              // 1. 创建或更新方向箭头 (蓝色三角箭头)
              if (!window.__userHeadingMarker) {
                var headingSvg = '<svg width="70" height="70" viewBox="0 0 70 70" xmlns="http://www.w3.org/2000/svg">' +
                  '<defs>' +
                    '<filter id="arrowShadow" x="-50%" y="-50%" width="200%" height="200%">' +
                      '<feGaussianBlur in="SourceAlpha" stdDeviation="2"/>' +
                      '<feOffset dx="0" dy="2" result="offsetblur"/>' +
                      '<feComponentTransfer>' +
                        '<feFuncA type="linear" slope="0.35"/>' +
                      '</feComponentTransfer>' +
                      '<feMerge>' +
                        '<feMergeNode/>' +
                        '<feMergeNode in="SourceGraphic"/>' +
                      '</feMerge>' +
                    '</filter>' +
                  '</defs>' +
                  // 蓝色三角形箭头 (指向上方)
                  '<g filter="url(#arrowShadow)">' +
                    '<path d="M 35 12 L 50 38 L 35 35 L 20 38 Z" fill="#2979FF" stroke="#FFFFFF" stroke-width="2.5" stroke-linejoin="round"/>' +
                  '</g>' +
                  '</svg>';
                var headingIcon = new AMap.Icon({
                  size: new AMap.Size(70, 70),
                  image: 'data:image/svg+xml;base64,' + btoa(headingSvg),
                  imageSize: new AMap.Size(70, 70)
                });
                window.__userHeadingMarker = new AMap.Marker({
                  position: lngLat,
                  icon: headingIcon,
                  anchor: 'center',
                  zIndex: 200,
                  angle: headingAngle,
                  title: '方向'
                });
                map.add(window.__userHeadingMarker);
              } else {
                window.__userHeadingMarker.setPosition(lngLat);
                var startAngle = window.__userHeadingMarker.getAngle() || 0;
                var endAngle = headingAngle;
                var diff = endAngle - startAngle;
                if (diff > 180) diff -= 360;
                if (diff < -180) diff += 360;

                if (Math.abs(diff) > 1) {
                  var duration = 300;
                  var startTime = performance.now();
                  function step(now) {
                    var t = (now - startTime) / duration;
                    if (t >= 1) {
                      window.__userHeadingMarker.setAngle(endAngle);
                      return;
                    }
                    t = 1 - Math.pow(1 - t, 3);
                    window.__userHeadingMarker.setAngle(startAngle + diff * t);
                    requestAnimationFrame(step);
                  }
                  requestAnimationFrame(step);
                } else {
                   window.__userHeadingMarker.setAngle(endAngle);
                }
              }

              // 2. 创建或更新中心白色圆点
              if (!window.__userDotMarker) {
                var dotSvg = '<svg width="48" height="48" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">' +
                  '<defs>' +
                    '<filter id="circleShadow" x="-50%" y="-50%" width="200%" height="200%">' +
                      '<feGaussianBlur in="SourceAlpha" stdDeviation="2.5"/>' +
                      '<feOffset dx="0" dy="1.5" result="offsetblur"/>' +
                      '<feComponentTransfer>' +
                        '<feFuncA type="linear" slope="0.35"/>' +
                      '</feComponentTransfer>' +
                      '<feMerge>' +
                        '<feMergeNode/>' +
                        '<feMergeNode in="SourceGraphic"/>' +
                      '</feMerge>' +
                    '</filter>' +
                  '</defs>' +
                  // 白色圆圈 + 蓝色边框
                  '<g filter="url(#circleShadow)">' +
                    '<circle cx="24" cy="24" r="12" fill="#FFFFFF" stroke="#2979FF" stroke-width="3"/>' +
                  '</g>' +
                  '</svg>';
                var dotIcon = new AMap.Icon({
                  size: new AMap.Size(48, 48),
                  image: 'data:image/svg+xml;base64,' + btoa(dotSvg),
                  imageSize: new AMap.Size(48, 48)
                });
                window.__userDotMarker = new AMap.Marker({
                  position: lngLat,
                  icon: dotIcon,
                  anchor: 'center',
                  zIndex: 199,
                  title: '当前位置'
                });
                map.add(window.__userDotMarker);
              } else {
                window.__userDotMarker.setPosition(lngLat);
              }
            }

            if (userLocation && window.ensureUserMarker) {
              window.ensureUserMarker(userLocation, userHeading);
            }
          } catch (e) {
            window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify({ type:'mapError', error: e.message }));
          }
        }
      </script>
    </body>
    </html>`;
  }, [shouldRenderMap, region, attractions, currentLocation]); // heading 不再作为依赖，避免重建 HTML

  // 优化：使用 useCallback 缓存回调函数
  const handleMessage = useCallback(
    e => {
      try {
        const data = JSON.parse(e.nativeEvent.data);

        if (data.type === 'mapReady') {
          setWebMapReady(true);
        }
        if (data.type === 'mapError') {
          setWebMapReady(false);
        }
        if (data.type === 'markerClick') {
          const a = attractions.find(
            x =>
              (x.id && String(x.id) === String(data.id)) ||
              x.name === data.title,
          );
          if (a) {
            onPressMarker?.(a);
          }
        }
      } catch {}
    },
    [attractions, onPressMarker],
  );

  // 回到当前位置（不强制刷新 WebView）
  const handleBackToCurrentLocation = useCallback(() => {
    if (currentLocation && webViewRef.current) {
      const script = `
        (function(){
          if (!window.map) { return; }
          var target = new AMap.LngLat(${Number(
            currentLocation.longitude,
          )}, ${Number(currentLocation.latitude)});
          window.map.setZoom(Math.max(window.map.getZoom(), 14));
          window.map.panTo(target);
        })();
        true;
      `;
      webViewRef.current.injectJavaScript(script);
    } else if (onLocationPress) {
      onLocationPress();
    }
  }, [currentLocation, onLocationPress]);

  // 优化：处理触摸事件，解决与 FlatList 的滑动冲突
  const handleTouchStart = useCallback(e => {
    isTouchingMap.current = true;
    touchStartY.current = e.nativeEvent.pageY;
    touchStartX.current = e.nativeEvent.pageX;
  }, []);

  const handleTouchMove = useCallback(e => {
    if (!isTouchingMap.current) return false;

    const deltaY = Math.abs(e.nativeEvent.pageY - touchStartY.current);
    const deltaX = Math.abs(e.nativeEvent.pageX - touchStartX.current);

    // 如果水平滑动大于垂直滑动，拦截事件（地图操作）
    // 如果垂直滑动小于阈值，也拦截事件（可能是点击或地图缩放）
    if (deltaX > deltaY || deltaY < scrollThreshold.current) {
      return true; // 拦截事件，不传递给父组件
    }

    return false; // 允许垂直滚动传递给 FlatList
  }, []);

  const handleTouchEnd = useCallback(() => {
    isTouchingMap.current = false;
    touchStartY.current = 0;
    touchStartX.current = 0;
  }, []);

  return (
    <View style={[styles.wrapper, style]}>
      <View
        style={[styles.container, style]}
        pointerEvents="box-none"
        onResponderMove={handleTouchMove}
        onResponderGrant={handleTouchStart}
        onResponderRelease={handleTouchEnd}
        onResponderTerminate={handleTouchEnd}
      >
        {shouldRenderMap ? (
          <WebView
            ref={webViewRef}
            source={{ html }}
            style={styles.web}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            startInLoadingState={true}
            scalesPageToFit={false}
            androidLayerType="hardware"
            androidHardwareAccelerationDisabled={false}
            cacheEnabled={true}
            cacheMode="LOAD_CACHE_ELSE_NETWORK"
            scrollEnabled={true}
            bounces={false}
            decelerationRate={0.99}
            mixedContentMode="compatibility"
            thirdPartyCookiesEnabled={true}
            nestedScrollEnabled={true}
            overScrollMode="never"
            showsVerticalScrollIndicator={false}
            showsHorizontalScrollIndicator={false}
            onMessage={handleMessage}
            renderLoading={() => null}
          />
        ) : null}

        {/* 移除加载动画遮罩 */}
      </View>

      {/* 定位按钮 - 放在容器外面避免触摸事件被拦截 */}
      {webMapReady && currentLocation && (
        <TouchableOpacity
          style={styles.locationBtn}
          onPress={handleBackToCurrentLocation}
          activeOpacity={0.7}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <Text style={styles.locationTxt}>📍</Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

WebAmap.displayName = 'WebAmap';

// 自定义比较函数，只在关键数据真正变化时才重新渲染
function arePropsEqual(prevProps, nextProps) {
  // 比较城市名
  if (prevProps.city !== nextProps.city) return false;

  // heading 变化需要触发组件更新，以便 useEffect 注入最新角度到 WebView
  if (prevProps.heading !== nextProps.heading) return false;

  // 比较地图区域（坐标变化超过 0.001 才重新渲染）
  if (prevProps.region?.latitude && nextProps.region?.latitude) {
    const latDiff = Math.abs(
      prevProps.region.latitude - nextProps.region.latitude,
    );
    const lngDiff = Math.abs(
      prevProps.region.longitude - nextProps.region.longitude,
    );
    if (latDiff > 0.001 || lngDiff > 0.001) return false;
  } else if (prevProps.region !== nextProps.region) {
    return false;
  }

  // 比较当前位置
  if (prevProps.currentLocation !== nextProps.currentLocation) {
    if (!prevProps.currentLocation && nextProps.currentLocation) return false;
    if (prevProps.currentLocation && !nextProps.currentLocation) return false;
    if (prevProps.currentLocation && nextProps.currentLocation) {
      const latDiff = Math.abs(
        prevProps.currentLocation.latitude - nextProps.currentLocation.latitude,
      );
      const lngDiff = Math.abs(
        prevProps.currentLocation.longitude -
          nextProps.currentLocation.longitude,
      );
      if (latDiff > 0.001 || lngDiff > 0.001) return false;
    }
  }

  // 比较景点数组（只比较长度和ID列表，避免深度比较整个对象）
  if (prevProps.attractions.length !== nextProps.attractions.length)
    return false;

  // 如果长度相同，比较景点的 ID 列表
  const prevIds = prevProps.attractions.map(a => a.id).join(',');
  const nextIds = nextProps.attractions.map(a => a.id).join(',');
  if (prevIds !== nextIds) return false;

  // 其他 props 不参与比较（回调函数每次都会变化，但不影响渲染）
  return true;
}

export default React.memo(WebAmap, arePropsEqual);

const styles = StyleSheet.create({
  wrapper: {
    position: 'relative',
    height: 300,
  },
  container: {
    height: 300,
    borderRadius: 12,
    overflow: 'hidden',
    backgroundColor: COLORS.background.secondary,
    position: 'relative',
  },
  web: {
    flex: 1,
    backgroundColor: 'transparent',
    // 性能优化：优化 WebView 渲染
    opacity: 0.99, // 触发硬件加速
  },
  loading: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.background.secondary,
  },
  loadingIcon: { fontSize: 32, marginBottom: 6 },
  loadingTitle: { fontSize: 16, fontWeight: '600', color: COLORS.text.primary },
  loadingSub: { fontSize: 12, color: COLORS.text.tertiary, marginTop: 4 },
  placeholder: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.background.secondary,
  },
  blurOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(15, 23, 42, 0.45)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  shimmer: {
    width: '70%',
    maxWidth: 280,
    height: 140,
    borderRadius: 20,
    backgroundColor: 'rgba(255,255,255,0.12)',
    position: 'absolute',
    transform: [{ rotate: '-5deg' }],
  },
  overlayContent: {
    alignItems: 'center',
  },
  locationBtn: {
    position: 'absolute',
    bottom: 12,
    right: 12,
    width: 50,
    height: 50,
    backgroundColor: COLORS.background.card,
    borderRadius: 25,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 10,
    zIndex: 9999,
    shadowColor: COLORS.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3,
  },
  locationTxt: {
    fontSize: 20,
  },
});
